package org.jet.emall.log;

import org.jet.emall.rbac.dto.AdminBaseLogDTO;

import org.jet.emall.rbac.dto.AdminLoginLogDTO;
import org.jet.emall.rbac.dto.AdminOpLogDTO;
import org.jet.emall.rbac.service.CustomAdminLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-14 16:34
 */
@Component
public class ThreadPoolUtil {

    /**
     * 创建线程池
     *
     */
    ExecutorService threadPool = Executors.newFixedThreadPool(20);
    /**
     * 创建原生阻塞队列  队列最大容量为1000
     *
     */
    BlockingQueue<AdminBaseLogDTO> queue = new ArrayBlockingQueue<>(1000);

    @Autowired
    private CustomAdminLogService adminLogService;

    public ThreadPoolUtil(){

        for(int i=0;i<20;i++){
            threadPool.execute(()->{
                while (true) {
                    try {
                        AdminBaseLogDTO dto = queue.take();
                        if( dto instanceof AdminOpLogDTO) {
                            adminLogService.saveOperationLog((AdminOpLogDTO) dto);
                        }else if( dto instanceof AdminLoginLogDTO){
                            adminLogService.saveLoginLog((AdminLoginLogDTO) dto);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public void addTask(AdminBaseLogDTO adminBaseLogDTO){
        queue.add(adminBaseLogDTO);
    }


}
